package com.xtravel.common.helper;

import com.xtravel.common.widget.AsyncImageView;

import java.util.ArrayList;
import java.util.List;

public class AsyncBitmapManager
{

	private static AsyncBitmapManager _instanse = new AsyncBitmapManager();

	public static AsyncBitmapManager getInstanse()
	{
		return _instanse;
	}

	private List<LazyLoader> lazyLoaderList;

	public AsyncBitmapManager()
	{
		this.lazyLoaderList = new ArrayList<LazyLoader>();
	}

	public void put(int postion, String imageUrl, AsyncImageView imageView)
	{
		LazyLoader loader = new LazyLoader();
		loader.position = postion;
		loader.imageUrl = imageUrl;
		loader.imageView = imageView;

		if (!exists(loader))
		{
			this.lazyLoaderList.add(loader);
		}
	}

	public void show(int minPostion, int maxPostion)
	{
		clearLazyLoaderList(minPostion, maxPostion);
		startDownload();
	}

	private void startDownload()
	{
		for (LazyLoader lazyLoader : lazyLoaderList)
		{
			lazyLoader.imageView.setImageUrl(lazyLoader.imageUrl);
			/*
			if (!lazyLoader.imageView.isLoaded(lazyLoader.imageUrl))
			{
				lazyLoader.imageView.setImageUrl(lazyLoader.imageUrl);
			}
			*/
		}
	}

	private void clearLazyLoaderList(int minPostion, int maxPostion)
	{
		for (int i = lazyLoaderList.size() - 1; i >= 0; i--)
		{
			LazyLoader loader = lazyLoaderList.get(i);
			if (loader.position < minPostion || loader.position > maxPostion)
			{
				loader.imageView.setImageUrl(null);
				// lazyLoaderList.remove(loader);
			}
		}
	}

	private Boolean exists(LazyLoader loader)
	{
		for (LazyLoader lazyLoader : lazyLoaderList)
		{
			if (lazyLoader.position == loader.position && lazyLoader.imageUrl == loader.imageUrl)
			{
				return true;
			}
		}

		return false;
	}

	class LazyLoader
	{
		public int position;
		public String imageUrl;
		public AsyncImageView imageView;

	}

}
